from django import forms
from django.shortcuts import render, redirect, HttpResponse
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from mysite import models
from mysite.utills.pagenation import Pagination
from mysite.utills.bootstrap import BootStrapModelForm

# def pretty_list(request):
#     """靓号管理"""
#     data_dict = {}
#     # 搜索功能,如果传参根据传参来，如果没传参，获取所有
#     # mobile__contains data_dict中手机号包含value的结果
#     value = request.GET.get("q", '')
#     if value:
#         data_dict['mobile__contains'] = value
#
#
#
#
#     # 分页功能
#     page = int(request.GET.get('page', 1))
#     page_size = 10
#     start = (page-1)*page_size
#     end = page * page_size
#
#     queryset = models.PrettyNumbers.objects.filter(**data_dict).order_by('-level')[start:end]
#
#     # 数据总条数
#     total_count = models.PrettyNumbers.objects.filter(**data_dict).order_by('-level').count()
#     # 计算总页码
#     total_page_count, div = divmod(total_count, page_size)
#     if div:
#         total_page_count += 1
#
#     # 显示当前页前五页后五页
#     plus = 5
#     if total_page_count <= 2 * plus + 1:
#         start_page = 1
#         end_page = total_page_count
#     else:
#         # 当前页小于5的时候
#         if page <= plus:
#             start_page = 1
#             end_page = 2 * plus + 1
#         else:
#             if (page+plus) > total_page_count:
#                 start_page = total_page_count - 2*plus
#                 end_page = total_page_count
#             else:
#                 start_page = page - plus
#                 end_page = page + plus
#     # 页码
#     page_str_list = []
#
#     # 首页
#     pre = '<li><a href="?page={}">首页</a></li>'.format(1)
#
#     # 上一页
#     if page > 1:
#         pre = '<li><a href="?page={}">上一页</a></li>'.format(page-1)
#         page_str_list.append(pre)
#     else:
#         pre = '<li><a href="?page={}">上一页</a></li>'.format(1)
#     page_str_list.append(pre)
#
#     # 页面
#     for i in range(start_page, total_page_count+1):
#         ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
#         page_str_list.append(ele)
#
#     # 下一页
#     if page < total_page_count:
#         pre = '<li><a href="?page={}">下一页</a></li>'.format(page+1)
#         page_str_list.append(pre)
#     else:
#         pre = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
#     page_str_list.append(pre)
#
#     # 尾页
#     pre = '<li><a href="?page={}">尾页</a></li>'.format(total_page_count)
#
#
#     return render(request, 'pretty_list.html', {'queryset': queryset, 'value': value})
def pretty_list(request):
    """ 靓号列表 """

    # 搜索
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = models.PrettyNumbers.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request, queryset, page_size=10)

    context = {
        "search_data": search_data,
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, 'pretty_list.html', context)


class PrettyModelForm(forms.ModelForm):
    class Meta:
        model = models.PrettyNumbers
        # 取所有字段
        # fields = '__all__'
        fields = ['mobile', 'price', 'status', 'level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有插件添加样式form-control
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control'}

    # 校验手机号码长度   钩子方法
    def clean_mobile(self):
        user_mobile = self.cleaned_data['mobile']

        exists = models.PrettyNumbers.objects.filter(mobile=user_mobile).exists()
        if exists:
            raise ValidationError('手机号已存在')

        if len(user_mobile) != 11:
            raise ValidationError('手机号格式错误')
        return user_mobile

def pretty_add(request):
    """添加靓号"""
    if request.method == 'GET':
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})

    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list')
    return render(request, 'pretty_add.html', {'form': form})



class PrettyEditModelForm(forms.ModelForm):

    # mobile = forms.CharField(disabled=True, label='手机号')

    class Meta:
        model = models.PrettyNumbers

        fields = ['price', 'status', 'level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有插件添加样式form-control
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder':field.label}

    # 校验手机号码长度   钩子方法
    def clean_mobile(self):

        user_mobile = self.cleaned_data['mobile']
        # 排除自己，校验与其他号码是否重复
        exists = models.PrettyNumbers.objects.exclude(id=self.isinstance.pk).filter(mobile=user_mobile).exists()
        if exists:
            raise ValidationError('手机号已存在')
        return user_mobile


def pretty_edit(request, nid):
    """编辑靓号"""
    row_object = models.PrettyNumbers.objects.filter(id=nid).first()

    if request.method == 'GET':
        form = PrettyEditModelForm
        # 根据id获取编辑的那一行的数据
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {'form': form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list')
    return render(request, 'pretty_edit.html', {'form': form})

def pretty_delete(request, nid):
    models.PrettyNumbers.objects.filter(id=nid).first().delete()
    return redirect('/pretty/list')



























